package io.renren.modules.mqtt;

import io.renren.modules.mqtt.entity.MqttEvent;
import io.renren.modules.mqtt.service.IEventService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * //Add the class description
 *
 * @author lhb
 * @date 2023/6/12
 */

@Component
@Slf4j
public class EventServiceFactory implements InitializingBean, ApplicationContextAware {

    private ApplicationContext applicationContext;

    private final static Map<String, IEventService> EVENT_SERVICE_MAP = new HashMap<>();

    @Override
    public void afterPropertiesSet() throws Exception {
        applicationContext.getBeansOfType(IEventService.class)
                .values()
                .forEach(h -> EVENT_SERVICE_MAP.put(h.getMessType(), h));
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    public static boolean handleEventMessage(MqttEvent event) {
        try {
            // 根据消息类型，查找对应类型处理机制
            IEventService eventService = EVENT_SERVICE_MAP.get(event.getMsgType());
            return eventService.eventHandler(event);
        } catch (Exception e) {
            log.debug("处理MqttEvent：msgType={}, accessId={}, terminalNo={} 异常{}", event.getMsgType(), event.getAccessId(), event.getTerminalNo(), e.getMessage());
            log.debug(e.toString());
        }
        return false;
    }
}
